// 云函数入口文件
const cloud = require('wx-server-sdk')
const moment = require("moment")
const MAX_LIMIT = 100

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
  const db = cloud.database()
  const _ = db.command

  const userCount = await db.collection('user').where({
    isMember: true
  }).count()
  const userTotal = userCount.total
  // 计算需分几次取
  const userBatchTimes = Math.ceil(userTotal / 100)
  const userTasks = []
  for (let i = 0; i < userBatchTimes; i++) {
    const promise = db.collection('user').where({
      isMember: true,
      isOut: false
    }).orderBy('point', 'desc').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    userTasks.push(promise)
  }
  const userData = (await Promise.all(userTasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
  let userList = userData.data

  var stratMonth = moment()
  stratMonth.locale('zh-cn');
  stratMonth.set({year:2023,month:5, date:"1", hour: 0, minute: 0, second: 0, millisecond: 0 })
  const startMonthDate = stratMonth.startOf('month').valueOf();
  console.log("startMonth:"+stratMonth.startOf('month').format('lll'))
  var endMonth = moment()
  endMonth.set({ hour: 0, minute: 0, second: 0, millisecond: 0 })
  const endMonthDate = endMonth.endOf('month').valueOf();
  console.log("endMonth:"+endMonth.endOf('month').format('lll'))

  for (var i = 0; i < userList.length; i++) {
    let user = userList[i]
    const monthCount = await db.collection('cards').where({
      _openid: user._openid,
      systemTime: _.lte(endMonthDate).and(_.gte(startMonthDate)),
    }).count()
    var monthPoints = [0, 0, 0, 0, 0, 0, 0]
    var totleMonthPoint = 0
    if (monthCount.total > 0) {
      const monthTotal = monthCount.total
      // 计算需分几次取
      const monthBatchTimes = Math.ceil(monthTotal / 100)
      const monthTasks = []
      for (let i = 0; i < monthBatchTimes; i++) {
        const promise = db.collection('cards').where({
          _openid: user._openid,
          systemTime: _.lte(endMonthDate).and(_.gte(startMonthDate)),
        }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
        monthTasks.push(promise)
      }
      const monthCards = (await Promise.all(monthTasks)).reduce((acc, cur) => {
        return {
          data: acc.data.concat(cur.data),
          errMsg: acc.errMsg,
        }
      })
      let monthCardList = monthCards.data;
      for (var j = 0; j < monthCardList.length; j++) {
        let card = monthCardList[j]
        if (card.status == 'checked') {
          monthPoints[card.type.index] = monthPoints[card.type.index] + card.point
        }
      }
      for (var k = 0; k < monthPoints.length; k++) {
        totleMonthPoint = parseInt(totleMonthPoint) + parseInt(monthPoints[k])
      }
      console.log('user', user.nickName)
      console.log('totleMonthPoint', totleMonthPoint)
    }

    db.collection('userInfo').where({
      _openid: user._openid,
    }).update({
      data:{
        point:totleMonthPoint
      }
    })

    // db.collection('userInfo').where({
    //   _openid: user._openid,
    // }).update({
    //   data:{
    //     point:totleMonthPoint
    //   }
    // })

  }

  return {
    success:true
  };
}